import Vue from 'vue'
import {
	Consts
} from "../constants/constants";

const Storage = {
	getUserToken: () => {
		try {
			return JSON.parse(uni.getStorageSync(Consts.USER_INFO) || '{}').token
		} catch (e) {
			console.log('获取信息失败：\n', e)
		}
		return null;
	},
	setUserInfo: (userInfo, token) => {
		try {
			userInfo.headPortrait = userInfo.photo
			userInfo.token = token
			uni.setStorageSync(Consts.USER_INFO, JSON.stringify(userInfo))
		} catch (e) {
			console.log('保存信息失败：\n', e)
		}
	},
	getUserInfo: () => {
		let session = {}
		try {
			session = JSON.parse(uni.getStorageSync(Consts.USER_INFO) || '{}')
		} catch (e) {
			console.log('获取信息失败：\n', e)
		}
		return session;
	},
	clearUserInfo: () => {
		uni.setStorageSync(Consts.USER_INFO, '{}')
	},
	setData: (key, object) => {
		try {
			if (Object.prototype.toString.call(object) === '[object Object]' &&
				(JSON.stringify(object) === '{}'|| JSON.stringify(object) === '[]') ) {
				uni.setStorageSync(key + '_object', JSON.stringify(object))
			} else {
				uni.setStorageSync(key, object)
			}
		} catch (e) {
			console.log('保存信息失败：\n', e)
		} finally {}
	},
	getData: (key) => {
		let data = null;
		try {
			data = uni.getStorageSync(key + '_object')
			if (data) {
				data = JSON.parse(data);
			} else {
				data = uni.getStorageSync(key)
			}
			return data
		} catch (e) {
			console.log('获取信息失败：\n', e)
		} finally {
			// console.log('key:' + key + ';data:', data)
		}
		return null;
	},
	clearData: () => {
		console.log('清除缓存')
		try {
			uni.clearStorageSync()
			// let keys = uni.getStorageSync('session_storage_keys');
			// if (keys && keys.length > 0) {
			//     keys.map(key => {
			//         uni.storage.removeItem(key)
			//     })
			// }
		} catch (e) {
			console.log('清除信息失败：\n', e)
		}
	}
}


Vue.prototype.$Storage = Storage
export {
	Storage
}
